package top.shiyiri.regular;

import org.junit.Test;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Aunean
 * @date 2022/1/16 18:04
 */
public class ReTest {

    @Test
    public void test1() {

        String email = "1345@126.com";
        //定义邮箱的规则
        String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
        //boolean matches(String regex)：判断该字符串是否匹配指定的正则表达式
        boolean flag = email.matches(regex);
        //输出结果
        System.out.println("flag:"+flag);


        //String replaceAll(String regex, String replacement)：将该字符串所有匹配正则表达式的子串替换成指定的字符串
        String pattern = "\\d";
        String s = email.replaceAll(pattern, "-");
        System.out.println(s);//----@---.com

        //replaceFirst()将该字符串中第一个匹配正则表达式的子串替换成指定的字符串
        String s2 = email.replaceFirst(pattern, "-");
        System.out.println(s2);//-345@126.com

        //split(String regex)以regex为分隔符，将该字符串分割成多个子串
        String str = "12 34 345 234 13";
        String regex2 = "\\s";
        String[] split = str.split(regex2);
        System.out.println(Arrays.toString(split));//[12, 34, 345, 234, 13]
    }

    @Test
    public void test2() {
        //matches()：匹配字符串
        //find()：查找有没有满足条件的子串
        //group()：获取满足条件的子串
        String regex = "\\w(\\d\\d)(\\w+)";
        String testStr = "A22happy";
        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(testStr);
        if (matcher.find()) {
            int gc=matcher.groupCount();
            for (int i = 0; i <= gc; i++) {
                System.out.println("group "+i+" :"+matcher.group(i));
            }
        }
    }
}
